<?php

namespace app\command;

use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\services\WechatTemplateService;
use Carbon\Carbon;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Config;
use library\tools\Data;


class JobStat extends BasicCommand
{

    protected $name = 'stat:job';

    protected $desc = '测试命令程序';


     /**
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function execute(Input $input, Output $output)
    {

        $timeRange = $this->__getTimeRange();

        $agencyList = $this->__getagency();
        if(count($agencyList)){
            foreach ($agencyList as $store) {
                try {
                    $this->__handleStore($store, $timeRange);
                } catch (\Exception $e) {
                    dump($e->getMessage());
                }
            }
        }
        

    }


    /**
     * 处理一个店铺的数据
     * @param $store
     * @param $timeRange
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __handleStore($store, $timeRange)
    {

        $result = [
            'total'       => 0,
        ];
        //门店的接单数据统计
        $offset = ['offset' => 0, 'length' => 100];
        while (true) {
            $orderList = $this->__getTakeOrders($store, $offset, $timeRange);

            if (!$orderList) {
                unset($offset);
                break;
            }
            foreach ($orderList as $order) {
                $result['total'] += 1;
            }
            $offset['offset'] += $offset['length'];
        }
        Db::startTrans();
        $dayData = [
            'aid'               => Arr::get($store, 'id'),
            'provinces_id'      => Arr::get($store, 'provinces_id'),
            'city_id'           => Arr::get($store, 'city_id'),
            'for_time'          => Arr::get($timeRange, 'day'),
            'total'             => Arr::get($result, 'total'),
            'type'              => 1,
            'for_time_start'    => Arr::get($timeRange, 'dayTimeStart'),
            'for_time_end'      => Arr::get($timeRange, 'dayTimeEnd'),
            'created_at'        => Carbon::now()->getTimestamp(),
            'updated_at'        => Carbon::now()->getTimestamp(),
        ];
        $exitId = $this->__checkStatisticExit($dayData);

        if ($exitId!='-1') {
            $dayData['id'] = $exitId;
        }
        //门店日结算统计表
        $handleDay=Data::save("jobs_stat",$dayData);

        //门店月度结算统计
        $handleMonth = $this->__handleBusinessCycle($store, $timeRange, $result);

        if ($handleDay && $handleMonth) {
            echo "handle success";
            Db::commit();
        } else {
            echo "handle error";
            Db::rollback();
        }

    }

    /**
     * 门店周期报表处理
     * @param $store
     * @param $timeRange
     * @param $result
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __handleBusinessCycle($store, $timeRange, $result)
    {
        $cycleRange = $this->__getCycleRange($store, $timeRange);

        $businessStatMonth = Db::name('jobs_stat')
            ->where('aid', Arr::get($store, 'id'))
            ->where('provinces_id', Arr::get($store, 'provinces_id'))
            ->where('city_id', Arr::get($store, 'city_id'))
            ->where('type', 2)
            ->where('for_time_start', Arr::get($cycleRange, 'cycleTimeStart'))
            ->where('for_time_end', Arr::get($cycleRange, 'cycleTimeEnd'))
            ->find();

        if ($businessStatMonth) {
            $success = Db::name('jobs_stat')
                ->where('id', Arr::get($businessStatMonth, 'id'))
                ->update([

                    'total'       => Db::raw('total+'.Arr::get($result, 'total', 0)),
                    'for_time_end'      => Arr::get($cycleRange, 'newEndTime'),
                    'updated_at'        => Carbon::now()->getTimestamp(),
                ]);
        } else {
            $success = Db::name('jobs_stat')->insert([
                'aid'               => Arr::get($store, 'id'),
                'provinces_id'      => Arr::get($store, 'provinces_id'),
                'city_id'           => Arr::get($store, 'city_id'),
                'for_time'          => Arr::get($cycleRange, 'cycleTimeStart'),
                'total'             => Arr::get($result, 'total'),
                'for_time_start'    => Arr::get($cycleRange, 'cycleTimeStart'),
                'for_time_end'      => Arr::get($cycleRange, 'newEndTime'),
                'type'              => 2,
                'created_at'        => Carbon::now()->getTimestamp(),
                'updated_at'        => Carbon::now()->getTimestamp(),
            ]);
        }
        return $success;
    }

   

        /**
     * 获取门店周期统计时间节点
     * @param $store
     * @param $timeRange
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __getCycleRange($store, $timeRange)
    {
        $result = [];

        $date=date("Y-m");
        $tem = explode('-',$date); //切割日期 得到年份和月份
        $year = $tem['0'];
        $month = $tem['1'];
        $array=array( '1','3','5','7','8','01','03','05' ,' 07','08','10',' 12');
        if( in_array($month,$array))
        {
          $addDays = '31';
        }
        elseif( $month == 2 )
        {
          if ( $year%400 == 0 || ($year%4 == 0 && $year%100 !== 0) )    //判断是否是闰年
          {
            $addDays = '29';
          }
          else{
            $addDays = '28';
          }
        }
        else{
          $addDays = '30';
        }
        $addDays=$addDays-1;



        $hasRecord = Db::name('jobs_stat')
            ->where('type', 2)
            ->where('aid', Arr::get($store, 'id'))
            ->where('provinces_id', Arr::get($store, 'provinces_id'))
            ->where('city_id', Arr::get($store, 'city_id'))
            ->order('for_time_end DESC')
            ->find();
        
        if ($hasRecord && $hasRecord['for_time_start'] <= $timeRange['day'] && $hasRecord['for_time_end'] >= $timeRange['dayTimeEnd']) {
            $result = [
                'cycleTimeStart' => Arr::get($hasRecord, 'for_time_start'),
                'cycleTimeEnd' => Arr::get($hasRecord, 'for_time_end')
            ];
            $newEndTime = Carbon::createFromTimestamp(Arr::get($hasRecord, 'for_time_start'))
                ->addDays($addDays)->addHours(23)->addMinutes(59)->addSeconds(59)->getTimestamp();
            //结算周期调整过，需要判断最后日期点是否比昨天大
            if ($newEndTime >= $timeRange['dayTimeEnd']) {
                $result['newEndTime'] = $newEndTime;
            } else {
                //更新前一条的结算周期结束时间点
                Db::name('jobs_stat')->where('id', Arr::get($hasRecord, 'id'))
                    ->update([
                        'for_time_end' => Carbon::createFromTimestamp(Arr::get($timeRange, 'dayTimeEnd'))
                            ->addDays(-1)->getTimestamp()
                    ]);
            }
        }
        if (!Arr::get($result, 'newEndTime', 0)) {
            //获取新的时间节点
            $result = [
                'cycleTimeStart'    => Arr::get($timeRange, 'dayTimeStart'),
                'cycleTimeEnd'      => Carbon::createFromTimestamp(Arr::get($timeRange, 'dayTimeEnd'))->addDays($addDays)->getTimestamp(),
                'newEndTime'        => Carbon::createFromTimestamp(Arr::get($timeRange, 'dayTimeEnd'))->addDays($addDays)->getTimestamp()
            ];
        }
        return $result;
    }


     /**
     * 检查统计是否存在
     * @param $data
     * @return bool
     */
    private function __checkStatisticExit($data)
    {
        $exitId = Db::name('jobs_stat')
            ->where('aid', Arr::get($data, 'aid'))
            ->where('provinces_id', Arr::get($data, 'provinces_id'))
            ->where('city_id', Arr::get($data, 'city_id'))
            ->where('type', Arr::get($data, 'type'))
            ->where('for_time', Arr::get($data, 'for_time'))
            ->where('for_time_start', Arr::get($data, 'for_time_start'))
            ->where('for_time_end', Arr::get($data, 'for_time_end'))
            ->value('id');
        return $exitId ?: -1;
    }

    /**
     * 获取门店的订单
     * @param $store
     * @param $offset
     * @param $timeRange
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getTakeOrders($store, $offset, $timeRange)
    {   
        $data[]=['status','NEQ',0];
        $orderList = Db::name('Jobs')
            ->where($data)
            ->where('provinces_id', Arr::get($store, 'provinces_id'))
            ->where('city_id', Arr::get($store, 'city_id'))
            ->where('created_at', '>=', Arr::get($timeRange, 'dayTimeStart'))
            ->where('created_at', '<=', Arr::get($timeRange, 'dayTimeEnd'))
            ->limit(Arr::get($offset, 'offset'), Arr::get($offset, 'length'))
            ->order('created_at ASC')
            ->select();
        return $orderList ?: [];
    }


    /**
     * 获取所有的代理商
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getagency()
    {
        $agencyList = Db::name('system_agent_user')
            ->where('pid=0')
            ->field('id,provinces_id,city_id')
            ->select();
        return $agencyList ?: [];
    }



     /**
     * 获取统计时间节点
     * @return array
     */
    private function __getTimeRange()
    {
        return [
            'dayTimeStart'      => Carbon::yesterday()->getTimestamp(),
            'dayTimeEnd'        => Carbon::yesterday()->addHours(23)->addMinutes(59)->addSeconds(59)->getTimestamp(),
            'day'               => Carbon::yesterday()->getTimestamp(),
            'month'             => Carbon::yesterday()->startOfMonth()->getTimestamp(),//一个月的第一天
        ];
    }















}
